﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using CMN.Models;
using CMN.Models.Interfaces;
using CMN.Entity;
using CMN.Controllers;
using CMN.Controllers.Filters;
using CMN.Common;
using System.Text;
using CMN.UI;
using CMN.Framework;
using CMN.BLL;
using System.IO;
using System.Web.Security;
using System.Xml;
using CMN.Config;
namespace CMN.Controllers
{

    [LoggerFilter()]
    [ExceptionFilter()]
    [ExecutionTimingAttribute()]
    public class WeiXinController : Controller
    {
        [CompressFilter]
        [CacheFilterAttribute]
        public string Index()
        {
            SiteConfigInfo siteInfo = SiteConfigs.GetSiteConfig();
            weixin wx = new weixin(siteInfo.Token);
            String postStr = String.Empty;
           
            if (this.ControllerContext.HttpContext.Request.HttpMethod.ToUpper() == "POST")
            {
                Stream s = this.ControllerContext.HttpContext.Request.InputStream;
                Byte[] b = new Byte[s.Length];
                s.Read(b, 0, (Int32)s.Length);
                postStr = Encoding.UTF8.GetString(b);

                if (!String.IsNullOrEmpty(postStr))
                {
                    return wx.Handle(postStr);
                }
                else
                {
                    return string.Empty;
                }
            }
            else
            {
               return wx.Auth();
            }

        }



    }

 
   
 
public class weixin
{
    public weixin(string token)
    {
        this.Token = token;
    }
    private String Token = "";
    private String DefaultResponseContent = "欢迎关注生活百事通，生活中遇到问题赶快来搜索下哦！";
 
    public string Auth()
    {
        String echoStr = HttpContext.Current.Request.QueryString["echoStr"];
 
        if (CheckSignature())
        {
            if (!String.IsNullOrEmpty(echoStr))
            {
                return echoStr;
            }
        }
        return "";
    }
 //处理微信公众平台POST过来的数据
    public string Handle(String postStr)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(postStr);
 
        XmlElement rootElement = doc.DocumentElement;
        XmlNode MsgType = rootElement.SelectSingleNode("MsgType");
 
        RequestXML requestXML = new RequestXML();
        requestXML.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;
        requestXML.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;
        requestXML.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;
        requestXML.MsgType = MsgType.InnerText;
 
        if (requestXML.MsgType == "text")
        {
            requestXML.Content = rootElement.SelectSingleNode("Content").InnerText;
            //AppLog.Write(requestXML.Content, AppLog.LogMessageType.Debug);
        }
 
        else if (requestXML.MsgType == "location")
        {
            requestXML.Location_X = rootElement.SelectSingleNode("Location_X").InnerText;
            requestXML.Location_Y = rootElement.SelectSingleNode("Location_Y").InnerText;
            requestXML.Scale = rootElement.SelectSingleNode("Scale").InnerText;
            requestXML.MapInfo = rootElement.SelectSingleNode("Label").InnerText;
        }
 
        else if (requestXML.MsgType == "image")
        {
            requestXML.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText;
        }
 
      return  ResponseMsg(requestXML);
    }
 
    /// 验证微信签名
    private bool CheckSignature()
    {
        String signature = HttpContext.Current.Request.QueryString["signature"];
        String timestamp = HttpContext.Current.Request.QueryString["timestamp"];
        String nonce = HttpContext.Current.Request.QueryString["nonce"];
        String[] ArrTmp = { Token, timestamp, nonce };
 
        Array.Sort(ArrTmp);
        String tmpStr = String.Join("", ArrTmp);
 
        tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
        tmpStr = tmpStr.ToLower();
 
        if (tmpStr == signature)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
 
    /// <summary>
    /// 回复消息
    /// </summary>
    /// <param name="weixinXML"></param>
    private string ResponseMsg(RequestXML requestXML)
    {
        String responseContent = String.Empty;
        
        if (requestXML.MsgType == "text")
        {
            responseContent = FormatTextXML(requestXML.FromUserName, requestXML.ToUserName, requestXML.Content);
        }


        return responseContent;
    }
 
    /// 返回格式化文本XML内容
    private String FormatTextXML(String fromUserName, String toUserName, String content)
    {
        QueryParam qp = new QueryParam();
        qp.PageIndex = 1;
        qp.PageSize = 10;
        qp.Where = content;
        List<Module_ListInfo> list = new List<Module_ListInfo>();
        if (string.IsNullOrEmpty(content))
        {

        }
        LuceneHelper lucene = new LuceneHelper();

        list = lucene.Search(qp, "", false);


        Normal_ChannelEntity channel2 = null;
        SiteConfigInfo siteInfo = SiteConfigs.GetSiteConfig();
        foreach (Module_ListInfo listInfo in list)
        {
            channel2 = new Normal_ChannelEntity();
            channel2 = MvcWebCacheManager.GetNormal_ChannelByPath(listInfo.Path);
            if (channel2 != null)
            {
                listInfo.Url = string.Concat(siteInfo.Url.Replace("www","m"), channel2.DirectoryUrl, "/", (string.IsNullOrEmpty(siteInfo.ChannelUrl) ? listInfo.Id.ToString() : string.Format(siteInfo.ChannelUrl, listInfo.Id.ToString())));
            }
        }

        string strRetrun = string.Concat("<xml><ToUserName><![CDATA[", fromUserName, "]]></ToUserName><FromUserName><![CDATA[", toUserName, "]]></FromUserName><CreateTime>", ConvertDateTimeInt(DateTime.Now).ToString(), "</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>", list.Count.ToString(), "</ArticleCount><Articles>");
        foreach (Module_ListInfo listInfo in list)
        {
            strRetrun = string.Concat(strRetrun, "<item><Title><![CDATA[", listInfo.Title, "]]></Title><Description><![CDATA[", listInfo.Summary, "]]></Description><PicUrl><![CDATA[", string.Concat(siteInfo.Url,listInfo.Img), "]]></PicUrl><Url><![CDATA[", listInfo.Url, "]]></Url></item>");
        }
        strRetrun = string.Concat(strRetrun, "</Articles></xml>");
        return strRetrun;
    }
 
    private int ConvertDateTimeInt(System.DateTime time)
    {
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        return (int)(time - startTime).TotalSeconds;
    }
}
 
 
//微信请求类
public class RequestXML
{
    private String toUserName = String.Empty;
 
    /// <summary>
    /// 公众号
    /// </summary>
    public String ToUserName
    {
        get { return toUserName; }
        set { toUserName = value; }
    }
 
    private String fromUserName = "";
 
    /// <summary>
    /// 发送方微信号
    /// </summary>
    public String FromUserName
    {
        get { return fromUserName; }
        set { fromUserName = value; }
    }
 
    private String createTime = String.Empty;
 
    /// <summary>
    /// 创建时间
    /// </summary>
    public String CreateTime
    {
        get { return createTime; }
        set { createTime = value; }
    }
 
    private String msgType = String.Empty;
 
    /// <summary>
    /// 信息类型 地理位置:location,文本消息:text,消息类型:image
    /// </summary>
    public String MsgType
    {
        get { return msgType; }
        set { msgType = value; }
    }
 
    private String content = String.Empty;
 
    /// <summary>
    /// 信息内容
    /// </summary>
    public String Content
    {
        get { return content; }
        set { content = value; }
    }
 
    private String location_X = String.Empty;
 
    /// <summary>
    /// 地理位置纬度
    /// </summary>
    public String Location_X
    {
        get { return location_X; }
        set { location_X = value; }
    }
 
    private String location_Y = String.Empty;
 
    /// <summary>
    /// 地理位置经度
    /// </summary>
    public String Location_Y
    {
        get { return location_Y; }
        set { location_Y = value; }
    }
 
    private String scale = String.Empty;
 
    /// <summary>
    /// 地图缩放大小
    /// </summary>
    public String Scale
    {
        get { return scale; }
        set { scale = value; }
    }
 
    private String mapInfo = String.Empty;
 
    /// <summary>
    /// 地理位置信息
    /// </summary>
    public String MapInfo
    {
        get { return mapInfo; }
        set { mapInfo = value; }
    }
 
    private String picUrl = String.Empty;
 
    /// <summary>
    /// 图片链接
    /// </summary>
    public String PicUrl
    {
        get { return picUrl; }
        set { picUrl = value; }
    }
 }
}
